package autoTest.request;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import autoTest.command.ErrorCode;
import autoTest.command.Params;
import autoTest.database.DataElement;
import autoTest.database.DataManager;
import autoTest.utils.TextUtils;
import net.sf.json.JSONObject;

public class QuerryResultPart extends RequestPart {
	private static final long serialVersionUID = 2271797150647771296L;
	public QuerryResultPart() {}

	@Override public void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String taskIdId = req.getParameter(Params.TASK_ID);
		int code = 0;
		
		
		if (TextUtils.isEmpty(taskIdId)) {
			code = ErrorCode.ERR_PARAM_ERROR;
		}
		DataElement tag = DataManager.getResultElement(taskIdId);
		
		if (tag == null) {		//请求的结果已经返回
			code = ErrorCode.ERR_RESULT_RETURNED;
		} else if (tag.deviceIDStr2DeviceSet(tag.getDeviceSet()).size() > 0) {	//请求对应case正在运行
			code = ErrorCode.ERR_CASE_RUNNING;
		}
		
		resp.setCharacterEncoding("UTF-8");  
		resp.setContentType("text/plain");
		resp.setStatus(HttpServletResponse.SC_OK);
		PrintWriter pWriter = resp.getWriter();
		JSONObject joRet = new JSONObject();		//存储返回消息
		joRet.put(Params.CODE, code);
		if (code == 0) {
			joRet.put(Params.CASE_RESULT_LIST, tag.getResultStr());		//将已获得结果返回
			DataManager.removeResult(taskIdId);
		} else {
			joRet.put(Params.CASE_RESULT_LIST, null);
		}
		pWriter.println(joRet.toString());  
	}
}
